package Model;

import Helper.*;
import com.sun.rowset.CachedRowSetImpl;
import java.sql.SQLException;
import java.util.ArrayList;

import Database.DB;

abstract class Model {
    //人为制造的障碍，我只是想要继承几个属性，这将导致我无法继续继承我想继承的那几个方法
    //まあ~就算是人为制造的苦难，解决了还是很开心嘚儿！～
    private ArrayList<Record> cache = null;

    ArrayList<Record> all(String tableName) {
        init(tableName);

        return cache;
    }

    ArrayList<Record> find(String tableName, int id) {
        init(tableName);

        ArrayList<Record> matches = new ArrayList<>();
        for (Record item : cache) {
            if (item.id == id) {
               matches.add(item);
            }
        }

        return matches;
    }

    ArrayList<Record> find(String tableName, String name){
        DB db = new DB();

        CachedRowSetImpl res = db.select(tableName, name);

        return createRecordArr(res);
    }

    protected void init(String tableName) {
        if( cache == null ){
            DB db = new DB();

            CachedRowSetImpl res = db.get(tableName);

            cache = createRecordArr(res);
        }
    }

    ArrayList<Record> createRecordArr(CachedRowSetImpl res){
        ArrayList<Record> result = new ArrayList<>();

        try {
            while (res.next()) {
                Record record = new Record();
                record.id = res.getInt(1);
                record.name = res.getString(2);

                result.add(record);
            }
        } catch (SQLException exception) {
            System.err.println("数据库出错！");
            if( Helper.isDev ){
                exception.printStackTrace();
            }
        }

        return result;
    }
}